<?php
/**
 * Created by PhpStorm.
 * User: smilezheng
 * Date: 2019/9/9
 * Time: 15:50
 */

namespace App\Lib;

use Generator;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;

class RequestBodyValueResolver implements ArgumentValueResolverInterface
{

    /**
     * Whether this resolver can resolve the value for the given ArgumentMetadata.
     *
     * @param Request          $request
     * @param ArgumentMetadata $argument
     *
     * @return bool
     */
    public function supports(Request $request, ArgumentMetadata $argument)
    {
        return $argument->getName() === 'content';
    }

    /**
     * Returns the possible value(s).
     *
     * @param Request          $request
     * @param ArgumentMetadata $argument
     *
     * @return Generator
     */
    public function resolve(Request $request, ArgumentMetadata $argument)
    {
        $content    = $request->getContent();
        $contentArr = json_decode($content, true);
        if (json_last_error() === JSON_ERROR_NONE) {
            yield $contentArr;
        } else {
            yield $content;
        }
    }
}
